<template>
  <div class="component-taked-medicine-list">
    <div
      v-for="(item, index) in takedMedicineList"
      :key="index"
      class="medicine-item"
    >
      <span class="select1">
        <label for="">药物名称：</label>
        <xm-remote-select
          :disabled="disabled"
          style="width: 150px"
          v-model="item.drugId"
          :defaults="defaults"
          :itemList="medicineList"
          @loadData="dtLoad"
          @seachData="querySearchDrugs"
          :isMultiple="false"
          :isFilterable="true"
          @change="(id) => handleSelectDrugs(id, index)"
        ></xm-remote-select>
      </span>
      <span class="select1">
        <label for="">使用频率：</label>
        <el-select
          v-model="item.frequency"
          style="width: 100px"
          filterable
          size="default"
          @change="updateModelValue"
        >
          <el-option
            v-for="item in frequencyList"
            :key="item.termChs"
            :label="item.termChs"
            :value="item.termChs"
          ></el-option>
        </el-select>
      </span>
      <span class="input1">
        <label for="">使用时长：</label>
        <el-input
          v-model.lazy="item.duration"
          :style="style"
          v-number
          placeholder=""
          max="100"
          size="default"
          @change="updateModelValue"
        ></el-input>
        天
      </span>

      <svg-icon
        v-if="!disabled"
        icon-class="close"
        @click="removeMedicineItem(index)"
      ></svg-icon>
    </div>
    <el-button type="text" @click="addMedicineItem">新增药物</el-button>
  </div>
</template>
<script>
  import { ArrowLeft, CirclePlus, CircleClose } from '@element-plus/icons-vue'
  import { useStore } from 'vuex'
  import { onBeforeMount, watch, ref, toRef } from 'vue'
  import XmRemoteSelect from 'XMC/XmRemoteSelect'
  import emr from '@/hooks/emr.vue'
  const { hashFrequencys, frequencys } = emr()
  import { searchList } from '@/api/modules/medicinal'
  import { cloneDeep } from 'lodash-es'
  import { isString } from '@/utils/validate'
  export default {
    name: 'TakedMedicineList',
    props: {
      modelValue: { type: String, default: '[]' },
      style: {
        type: String,
        default() {
          return 'width:100px;font-size:14px;'
        },
      },
      disabled: { type: Boolean, default: false },
    },
    emits: ['update:modelValue'],
    components: { XmRemoteSelect },
    setup(props, context) {
      let medicineList = ref([])
      let takedMedicineList = ref([])
      let defaults = ref([])

      onBeforeMount(async () => {
        medicineList.value = []
      })

      // 字符串转数组
      watch(
        () => props.modelValue,
        (val) => {
          if (isString(props.modelValue)) {
            let ret = []
            try {
              ret = JSON.parse(props.modelValue)
            } catch (err) {
              if (props.modelValue.length > 0) {
                takedMedicineList.value = []
                return
              }
              takedMedicineList.value = []
              return
            }

            takedMedicineList.value = ret
            console.log('defaults', ret)
            defaults.value = ret
              .filter((item) => item.drugId)
              .map((item) => {
                return {
                  id: item.drugId,
                  data: {
                    id: item.drugId,
                    medicineName: item.medicineName,
                    commonName: item.commonName,
                  },
                  label: `${item.medicineName}(通用名:${item.commonName})`,
                  value: item.drugId,
                }
              })
          }
        },
        { immediate: true, deep: true }
      )

      // methods
      function updateModelValue() {
        console.log(takedMedicineList.value)
        context.emit(
          'update:modelValue',
          JSON.stringify(takedMedicineList.value)
        )
      }
      function editMedicineByIdx(idx, data) {
        takedMedicineList.value[idx] = data
        updateModelValue()
      }
      function addMedicineItem() {
        takedMedicineList.value = takedMedicineList.value.concat([
          {
            id: '',
            drugId: '',
            commonName: '',
            medicineName: '',
            frequency: '',
            duration: '',
          },
        ])

        updateModelValue()
      }

      function removeMedicineItem(targetIndex) {
        takedMedicineList.value = takedMedicineList.value.filter(
          (item, index) => {
            return index != targetIndex
          }
        )

        updateModelValue()
      }
      async function querySearchDrugs(obj, cb) {
        if (!obj.val) return
        const res = await searchList({ name: obj.val })
        medicineList.value = res.data.map((item, index) => {
          return {
            value: item.id,
            // eslint-disable-next-line max-len
            label: `${item.medicineName}(通用名:${item.commonName})`,
            data: item,
          }
        })
      }

      async function dtLoad(cb) {
        cb()
      }

      function handleSelectDrugs(id, idx) {
        const item = medicineList.value.find((item) => item.value === id).data
        let target = takedMedicineList.value[idx]
        target.commonName = item.commonName
        target.medicineName = item.medicineName
        target.drugId = item.id

        updateModelValue()
      }

      return {
        takedMedicineList,
        frequencyList: frequencys,
        defaults: defaults,
        medicineList,
        updateModelValue,
        addMedicineItem,
        editMedicineByIdx,
        removeMedicineItem,
        querySearchDrugs,
        dtLoad,
        handleSelectDrugs,
      }
    },
  }
</script>
<style lang="scss">
  .component-taked-medicine-list {
    display: inline-block;

    .medicine-item {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      margin: 8px 0;

      & > * {
        margin-right: 12px;
        display: flex;
        justify-content: flex-start;
        align-items: center;

        & > label {
          margin-right: 8px;
        }
      }
    }
  }
</style>
